<?php

/* 
 * Table/IdealTable.php
 */
namespace RHX\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\Ideal;

class IdealTable extends AbstractTableGateway {

    protected $table = "rh_ideal";

    /**
     * Constructeur
     *
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new Ideal());
	$this->initialize();
    }
    
    /**
     * Tous les enregistrements
     * 
     * @return ResultSet
     */
    public function getAll(){
	return $this->select();
    }
    
    /**
     * Récupérer un enregistrement
     * 
     * @param int $id
     * @return Ideal
     */
    public function get($id){
	$row = $this->select(array('id' => $id))
		->current();
	return (!$row) ? null : $row;
    }
    
    /**
     * Effacer un enregistrement
     * 
     * @param int $id
     * @return int
     */
    public function erase($id){
	return $this->delete(array('id'=> $id));
    }
    
    /**
     * Sauvegarder
     * 
     * @param \RHX\Model\Object\Ideal $ideal
     * @return int
     */
    public function save(Ideal $ideal){
	$data = array(
	    'jour' => $ideal->jour,
	    'site' => $ideal->site,
	    'nb' => $ideal->nb,
	);
	$id = (int)$ideal->id;
	if($id == 0){
	    $this->insert($data);
	    return $this->getLastInsertValue();
	}elseif($this->get($id)){
	    $this->update($data, array('id' => $id));
	    return $id;
	}else{
	    return 0;
	}
    }
    
    /**
     * Rechecher le nombre ideal à partir d'une date et du site
     * 
     * @param string $date
     * @param int $site
     * @return Ideal
     */
    public function getIdeal($date, $site){
	$row = $this->select(array('jour' => $date, 'site' => $site))
		->current();
	return (!$row) ? null : $row;
    }
    
    /**
     * Récupérer tous les nombres de personne idéal sur une semaine
     * 
     * @param \RHX\Model\Object\Semaine $semaine
     * @param int $site
     * @return array
     */
    public function getWeekIdeal(\RHX\Model\Object\Semaine $semaine, $site){
	$dayName = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche');
	$ideals = array();
	foreach($dayName as $day){
	    //var_dump($semaine->$day);
	    $ideal = $this->getIdeal($semaine->$day, $site);
	    //var_dump($ideal);
	    $ideals[$day] = is_null($ideal) ? new Ideal() : $ideal;
	}
	return $ideals;
    }
}

